# -*- coding:utf-8 -*-
import configparser
import urllib
import base64
import hmac
import hashlib
import tools,wave,json,time,requests

class tts_util:
    AppId = 0
    SecretId = ""
    SecretKey = ""
    Expired = 3600
    conf=configparser.ConfigParser()

    def __init__(self):
        config_file_path = tools.resource_path("tts/conf.ini")
        self.conf.read(config_file_path, encoding="UTF-8")
        self.AppId = self.conf.getint("authorization", "AppId")
        self.SecretId = self.conf.get("authorization", "SecretId")
        self.SecretKey = self.conf.get("authorization", "SecretKey")

    def verify_param(self):
        if len(str(self.AppId)) == 0:
             print('AppId can not empty')
        if len(str(self.SecretId)) == 0:
             print('SecretId can not empty')
        if len(str(self.SecretKey)) == 0:
             print('SecretKey can not empty')

    def init_auth(self, appid, secret_id, secret_key):
        self.AppId = appid
        self.SecretId = secret_id
        self.SecretKey = secret_key

    def generate_sign(self, request_data):
        url = "tts.cloud.tencent.com/stream"
        sign_str = "POST" + url + "?"
        sort_dict = sorted(request_data.keys())
        for key in sort_dict:
            sign_str = sign_str + key + "=" + urllib.parse.unquote(str(request_data[key])) + '&'
        sign_str = sign_str[:-1]
        sign_bytes = sign_str.encode('utf-8')
        key_bytes = self.SecretKey.encode('utf-8')
        # print(sign_bytes)
        authorization = base64.b64encode(hmac.new(key_bytes, sign_bytes, hashlib.sha1).digest())
        return authorization.decode('utf-8')

    def text_to_wav(self,text, voice_type, destpath):
        print("generate audio file, text:%s" % (text))

        # request_data = collections.OrderedDict()
        request_data = dict()
        request_data['Action'] = 'TextToStreamAudio'
        request_data['AppId'] = self.AppId
        request_data['Codec'] = "pcm"
        request_data['Expired'] = int(time.time()) + self.Expired
        request_data['ModelType'] = 1
        request_data['SecretId'] = self.SecretId
        request_data['SessionId'] = "uopx"
        request_data['Speed'] = 0
        request_data['Text'] = text
        request_data['Timestamp'] = int(time.time())
        request_data['VoiceType'] = voice_type
        request_data['Volume'] = 0

        signature = self.generate_sign(request_data=request_data)

        header = {
            "Content-Type": "application/json",
            "Authorization": signature
        }
        url = "https://tts.cloud.tencent.com/stream"

        r = requests.post(url, headers=header, data=json.dumps(request_data), stream=True)

        i = 1
        wavfile = wave.open(destpath, 'wb')
        wavfile.setparams((1, 2, 16000, 0, 'NONE', 'NONE'))
        for chunk in r.iter_content(5000):
            if (i == 1) & (str(chunk).find("Error") != -1):
                raise Exception(chunk)
                print(str(chunk))
                return
            i = i + 1
            wavfile.writeframes(chunk)

        print("audio file saved")

        wavfile.close()
